<?php

namespace app\controllers;
use yii\data\ActiveDataProvider;
use app\models\MarketCategory;
use app\models\App;
use app\models\Languages;
use Yii;
use yii\web\NotFoundHttpException;
use yii\widgets\ActiveForm;

class MarketCategoryController extends \yii\web\Controller
{   
    public function behaviors()
    {   
        return [
            // 'verbs' => [
            //     'class' => VerbFilter::className(),
            //     'actions' => [
            //         'delete' => ['POST'],
            //     ],
            // ],
            'login' => [
                'class'   => \app\filters\LoginFilter::className()
            ],
        ];
    }
    
    public function actionIndex()
    {   
        // $data  = \app\models\UserLogin::getLoginedModel()->authedData;

        //     echo '<pre>';
        //     print_r($data);die;

        $query = MarketCategory::find();
        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => false
        ]);

        return $this->render('index', [
            'dataProvider' => $dataProvider
        ]);
    }

    //新建顶级分类，子分类
    public function actionCreate()
    {   
        $parent_id = \Yii::$app->request->get('id', 0);
        $model = new MarketCategory();

        if (\yii::$app->request->isPost) {
            \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            $multiFields = ['real_name'];
            $allowed_lang = Yii::$app->request->post('enable_lang',['en-us']);

            $model->attributes = Yii::$app->request->post('MarketCategory');
            $transaction = \Yii::$app->db->beginTransaction();
            if ($model->save()) {
                $lang_data = array();

                foreach ($multiFields as $field) {
                    $variable = Yii::$app->request->post($field, []);

                    foreach ($allowed_lang as $item) {
                        if (empty($item)) {
                            continue;
                        }
                        $lang_data[] = array(
                            'content'      => isset($variable[$item]) ? $variable[$item] : '',
                            'table_name'   => MarketCategory::tableName(),
                            'table_id'     => $model->id,
                            'table_field'  => $field,
                            'language'     => $item,
                            'created_time' => time(),
                            'updated_time' => time(),
                        );
                    }
                }
                if (empty($lang_data)) {
                    $transaction->rollback();
                    return [
                        'ok'    => -1,
                        'message' => \Yii::t('app', '至少选择一种语言'),
                    ];
                }
                foreach ($lang_data as $lang_data_value){
                    $GoodsLanguage = new Languages();
                    $GoodsLanguage->isNewRecord = true;
                    $GoodsLanguage->setAttributes($lang_data_value);
                    if (!$GoodsLanguage->save($lang_data_value)) {
                        $transaction->rollback();
                        $errors = current($GoodsLanguage->getErrors());
                        return [
                            'ok'    => -1,
                            'message' => \Yii::t('app', $errors[0]),
                        ];
                    }
                }
                $transaction->commit();
                return [
                    'ok'    => 0,
                    'message' => \Yii::t('app', '成功！'),
                ];
            }

            $errors = current($model->getErrors());
            return [
                'ok'    => -1,
                'message' => \Yii::t('app', $errors[0]),
            ];
        } else {
            //默认选中下拉框
            $model->parent_id = $parent_id;
            
            //所有分类数据
            $res = MarketCategory::find()->asArray()->all();

            // $ajaxdata['ok'] = 0;
            return $this->renderAjax('_form', [
                'model' => $model,
                'data' => $model->getDropDownList($res),
                'languages'    => Yii::$app->params['LANGUAGES'],
                'action' => 'create',
            ]);
        }
    }

    //删除分类
    public function actionDelete($id){
        //删除分类
        $model = new MarketCategory;
        $ids = $model::getChildCategory($id);
        $model->deleteAll(['id' => $ids]);

        //删除分类下对应的项目
        (new App)->deleteAll(['big_cate' => $ids]);

        //删除对应的翻译,
        (new Languages)->deleteAll(['table_name' => MarketCategory::tableName(), 'table_id' => $ids]);
        
        return $this->redirect(['index']);

    }

    //更新分类数据
    public function actionUpdate()
    {   
        $id = \Yii::$app->request->get('id', 0);
        $model = $this->findModel($id);

        if (\yii::$app->request->isPost) {
            \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            $multiFields = ['real_name'];
            $allowed_lang = Yii::$app->request->post('enable_lang',['en-us']);

            $post_data = Yii::$app->request->post('MarketCategory');
            $model->parent_id = $post_data['parent_id'];
            $model->name = $post_data['name'];

            $transaction = \Yii::$app->db->beginTransaction();
            if ($model->save()) {
                (new Languages())->deleteAll(['table_field' => $multiFields, 'table_id' => $model->id, 'table_name' => MarketCategory::tableName()]);

                $lang_data = array();

                foreach ($multiFields as $field) {
                    $variable = Yii::$app->request->post($field, []);

                    foreach ($allowed_lang as $item) {
                        if (empty($item)) {
                            continue;
                        }
                        $lang_data[] = array(
                            'content'      => isset($variable[$item]) ? $variable[$item] : '',
                            'table_name'   => MarketCategory::tableName(),
                            'table_id'     => $model->id,
                            'table_field'  => $field,
                            'language'     => $item,
                            'created_time' => time(),
                            'updated_time' => time(),
                        );
                    }
                }
                if (empty($lang_data)) {
                    $transaction->rollback();
                    return [
                        'ok'    => -1,
                        'message' => \Yii::t('app', '至少选择一种语言'),
                    ];
                }
                foreach ($lang_data as $lang_data_value){
                    $GoodsLanguage = new Languages();
                    $GoodsLanguage->isNewRecord = true;
                    $GoodsLanguage->setAttributes($lang_data_value);
                    if (!$GoodsLanguage->save($lang_data_value)) {
                        $transaction->rollback();
                        $errors = current($GoodsLanguage->getErrors());
                        return [
                            'ok'    => -1,
                            'message' => \Yii::t('app', $errors[0]),
                        ];
                    }
                }
                $transaction->commit();
                return [
                    'ok'    => 0,
                    'message' => \Yii::t('app', '成功！'),
                ];
            }

            $errors = current($model->getErrors());
            return [
                'ok'    => -1,
                'message' => \Yii::t('app', $errors[0]),
            ];
    
        } else {
            //计算下拉框的数据
            $res = MarketCategory::find()->asArray()->all();

            $lang_records_arr = array();
                

            if($model->languages){
                foreach ($model->languages as $item) {
                    $lang_records_arr[$item->language] = ['content'=>$item->content,'language'=>$item->language];
                }
            }
   
            return $this->renderAjax('_form', [
                'model' => $model,
                'data' => $model->getDropDownList($res),
                'languages'    => Yii::$app->params['LANGUAGES'],
                'lang_records' => $lang_records_arr,
                'action' => 'update',
            ]);
        }
    }

    /**
     * Finds the News model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return News the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = MarketCategory::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }


    /**
     * Displays a single Project model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        $projectCategory = new MarketCategory;
        return $this->render('view', [
            'model' => $this->findModel($id),
            'projectCategory' => $projectCategory,

        ]);
    }

}
